package com.zhyan8.bluetooth_c.discover;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.zhyan8.bluetooth_c.ChatActivity;
import com.zhyan8.bluetooth_c.R;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private DevicesAdapter adapter;
    private ArrayList<BluetoothDevice> list;
    private ScanDevices mScanDevices;

    public static final String[] permissions = {
            "android.permission.BLUETOOTH",
            "android.permission.BLUETOOTH_ADMIN",
            "android.permission.ACCESS_COARSE_LOCATION",
            "android.permission.BLUETOOTH_PRIVILEGED" };
    //Android12蓝牙权限申请
    private boolean bluePermission(){
        //compileSdkVersion项目中编译SDK版本大于30申请以下权限可使用
        //Manifest.permission.BLUETOOTH_SCAN、Manifest.permission.BLUETOOTH_ADVERTISE、Manifest.permission.BLUETOOTH_CONNECT
        //若小于30可以直接使用权限对应的字符串
        if (Build.VERSION.SDK_INT > 30) {
            if (
                    ContextCompat.checkSelfPermission(this, "android.permission.BLUETOOTH_SCAN") != PERMISSION_GRANTED
                            || ContextCompat.checkSelfPermission(this, "android.permission.BLUETOOTH_ADVERTISE") != PERMISSION_GRANTED
                            || ContextCompat.checkSelfPermission(this, "android.permission.BLUETOOTH_CONNECT") != PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(this, new String[]{
                        "android.permission.BLUETOOTH_SCAN",
                        "android.permission.BLUETOOTH_ADVERTISE",
                        "android.permission.BLUETOOTH_CONNECT"}, 1);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(Build.VERSION.SDK_INT>=23){
//            requestPermissions(permissions,1);
            if(bluePermission() == true){
                Log.d("bluePermission","bluePermission is ok");
            }else{
                Log.d("bluePermission","bluePermission is Nok");
            }
        }
        init();
    }

    private void init() {
        listView = (ListView) findViewById(R.id.listview);
        list = new ArrayList<>();
        adapter = new DevicesAdapter(this, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(icl);
        mScanDevices = new ScanDevices();
        initReceiver();
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);
    }

    public void onClick(View view){ //单击扫描按钮
        list.clear();
        list.addAll(mScanDevices.getBondedDevices()); //添加已绑定的设备列表
        adapter.notifyDataSetChanged();
        mScanDevices.startDiscovery(); //搜索周围蓝牙设备，并通过广播返回
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothDevice.ACTION_FOUND: //接收搜索到的蓝牙设备
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.d("find-onReceive","device:"+device.getAddress()+","+device.getName());
                    ParcelUuid[] uuids = device.getUuids();
                    for(ParcelUuid uuidIndex : uuids){
                        Log.d("find-onReceive","uuidIndex: " + uuidIndex.toString());
                    }
                    String address = device.getAddress();
                    for (int i = 0; i < list.size(); i++) { //避免接收重复的设备
                        if (address == null || address.equals(list.get(i).getAddress())) {
                            return;
                        }
                    }
                    list.add(device);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    AdapterView.OnItemClickListener icl = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String address = list.get(position).getAddress();
            startChat(address);
        }
    };

    private void startChat(String remoteAddress) {
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra("remoteAddress", remoteAddress);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}
